import { Request, Response } from 'express'
import { Room } from '../models/Room'
import { IUser } from '../models/User'

interface AuthRequest extends Request {
  user?: IUser
}

export const createRoom = async (req: AuthRequest, res: Response) => {
  try {
    const { title, description } = req.body
    if (!req.user) {
      return res.status(401).json({ message: '请先登录' })
    }

    const room = new Room({
      title,
      description,
      host: req.user._id,
    })

    await room.save()

    res.status(201).json({
      message: '创建成功',
      room: {
        id: room._id,
        title: room.title,
        streamKey: room.streamKey,
      },
    })
  } catch (error) {
    res.status(500).json({ message: '服务器错误' })
  }
}

export const getRooms = async (req: Request, res: Response) => {
  try {
    const rooms = await Room.find({ status: 'live' })
      .populate('host', 'username nickname avatar')
      .sort('-createdAt')

    res.json({ rooms })
  } catch (error) {
    res.status(500).json({ message: '服务器错误' })
  }
}

export const getRoomById = async (req: Request, res: Response) => {
  try {
    const room = await Room.findById(req.params.id).populate('host', 'username nickname avatar')

    if (!room) {
      return res.status(404).json({ message: '房间不存在' })
    }

    res.json({ room })
  } catch (error) {
    res.status(500).json({ message: '服务器错误' })
  }
}
